package com.li.springbootproject.config.rabbitmq;


import com.lidong.toolkit.constant.LogConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 8/11/2022 8:37 AM
 */
@Configuration
public class RabbitMqConfig {

    private static final Logger logger = LoggerFactory.getLogger(RabbitMqConfig.class);

    /**
     * 注册多例 bean
     *
     * @param connectionFactory connectionFactory
     * @return RabbitTemplate
     */
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public RabbitTemplate noSingleRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMandatory(true);
        return template;
    }

    /**
     * 创建 DEQUE_ONE 的 bean
     *
     * @return Queue
     */
    @Bean
    public Queue createDequeueOne() {
        logger.info(LogConst.LOG_SUCCESS_PREFIX + "消息队列 " + RabbitMqConst.DEQUE_ONE + "注册完成");
        return new Queue(RabbitMqConst.DEQUE_ONE);
    }

    /**
     * 创建 DEQUE_ONE 的 bean
     *
     * @return Queue
     */
    @Bean
    public Queue createDequeueTwo() {
        logger.info(LogConst.LOG_SUCCESS_PREFIX + "消息队列 " + RabbitMqConst.DEQUE_TWO + "注册完成");
        return new Queue(RabbitMqConst.DEQUE_TWO);
    }

    /**
     * 创建 DEQUE_ONE 的 bean
     *
     * @return Queue
     */
    @Bean
    public Queue createDequeueThree() {
        logger.info(LogConst.LOG_SUCCESS_PREFIX + "消息队列 " + RabbitMqConst.DEQUE_THREE + "注册完成");
        return new Queue(RabbitMqConst.DEQUE_THREE);
    }


    /**
     * 创建 ExchangeOne 的交换机
     *
     * @return FanoutExchange
     */
    @Bean
    public FanoutExchange exchangeOne() {
        logger.info(LogConst.LOG_SUCCESS_PREFIX + "交换机 " + RabbitMqConst.EXCHANGE_ONE_NAME + "注册完成");
        return new FanoutExchange(RabbitMqConst.EXCHANGE_ONE_NAME);
    }

    /**
     * 绑定队列一到交换机
     *
     * @return 绑定对象
     */
    @Bean
    public Binding bingQueue1ToExchange() {
        logger.info(LogConst.LOG_SUCCESS_PREFIX + "绑定队列一到交换机成功");
        return BindingBuilder.bind(createDequeueOne()).to(exchangeOne());
    }

    @Bean
    public Binding bingQueue2ToExchange() {
        logger.info(LogConst.LOG_SUCCESS_PREFIX + "绑定队列二到交换机成功");
        return BindingBuilder.bind(createDequeueTwo()).to(exchangeOne());
    }

}
